/***************************************************************
 *  Copyright (c) 2007 by GroupMe! Team (www.groupme.net)
 *  All rights reserved.
 *
 *  This file is part of the GroupMe! Project. Source code of 
 *  this project is closed and redistribution of this code is
 *  prohibited. 
 *  
 *  Contact: http://www.groupme.net
 *
 *  This copyright notice MUST APPEAR in all copies of the file!
 ***************************************************************/
package net.groupme.gui.rendering;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import de.nava.informa.core.ChannelIF;
import de.nava.informa.core.ParseException;
import de.nava.informa.impl.basic.ChannelBuilder;
import de.nava.informa.impl.basic.Item;
import de.nava.informa.parsers.FeedParser;

import net.groupme.exceptions.UpdateFailedException;
import net.groupme.gui.constants.VIEW_VOCABULARY;
import net.groupme.model.ObjectFactory;
import net.groupme.model.Resource;
import net.groupme.model.ResourceVisualization;
import net.groupme.utils.URLResolver;

/**
 * created on 10.07.2007
 * 
 * This class/interface...
 * 
 * @author Fabian Abel, <a href="mailto:abel@l3s.de">abel@l3s.de</a>
 * @author Mischa Frank, <a href="mailto:code@planetfrank.net">code@planetfrank.net</a>
 * @author last edited by: $Author: patrick $
 * 
 * @version $Revision: 1.8 $ $Date: 2008-11-19 14:26:22 $
 */
public class GroupRenderer extends AbstractRenderer {
	/** Logger for this class  */
	protected static final Log logger = LogFactory.getLog(GroupRenderer.class);

	public String renderContentAsHTML(String uRL, String uRI, String iD, String name) throws MalformedURLException{
		String html = "";
		// Die letzten 3 Items Hinzufügen
		html += "<div id=\"" + uRI + "_rssItems\" class=\"rssItem\">";
		html += "<strong><big>"+  name + "</strong></big> <br/> <br/>";
		// URL hinzufuegen
		if ((uRL != null) && (uRL != "")) {
			html +="<a href=\"" + uRL + "\" "
				 + "target=\"_blank\"" + "\" title=\"visit Group @ "
				 + uRL + "\">" 		 
				 +"<img src=\"" +   VIEW_VOCABULARY.GROUPME_BASE_URL 
				 + "/images/g-16x16.gif\" height=\"16px\" width=\"16px\" style=\"text-decoration:none;border:none;\" alt=\"\"/>"
				 +"<big> visit Group</big>"
				 + "</a>";
		}
		if ((uRL != null) && (uRL != "")){
			String groupID = iD;
			
			List<Item> itemList = getLatestItems( VIEW_VOCABULARY.GROUPME_BASE_URL+"api/export.do?groupID=" + groupID + "&mode=export-groups&export-format=rss");
			int i = 0;
			while (i < 10 && i < itemList.size()) {
				html += "<p> <a href=\"" + itemList.get(i).getLink()
					 + "\" target=\"_blank\"" + "\" title=\"visit resource @ "
					 + itemList.get(i).getLink() + "\">";
				if (itemList.get(i).getDate() != null){
					//Formatiere Datumstring
					Date rssDate = itemList.get(i).getDate();
					DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
					
					//html+= itemList.get(i).getDate()  + " - ";
					html+= df.format(rssDate)  + " - ";
				}else{
					html+= (i + 1) + ". - " ;
				}
				html+= itemList.get(i).getTitle() + "</a></p>";
				i++;
			}
			if (itemList.size() == 0) {
				html += "<br/> " + "<span style=\"font-size:2em;\">"
				     + "Problems parsing the feed or feed is empty"
					 + "</span>";
			}
		}
		html += "</div>";


		return html;
		
	}
	
	
	
	public String renderAsHTML(ResourceVisualization resourceVisualization,
			Integer groupWidth, Integer groupHeight, Integer zAxis) {
		String html = "";
		Resource resource = resourceVisualization.getResource();
		String width = "100px;";
		String widthMove = "100px;";
		
		if (resourceVisualization.getWidth() > 0) {
			width = " width:"
					+ (((resourceVisualization.getWidth() * groupWidth) / 1000) - 4)
					+ "px;";
			widthMove = " width:"
					+ (((resourceVisualization.getWidth() * groupWidth) / 1000))
					+ "px;";
		}
		// div initialisierung
		html += this.getDivAttributes(resourceVisualization, groupWidth,
				groupHeight, zAxis);
		// menu:
		html += this.getMenu(resourceVisualization, resourceVisualization
				.getURI().toString(), groupWidth);
		// div open _content
		html += "<div id=\""
				+ resourceVisualization.getURI().toString()
				+ "_content\" style=\""
				+ width
				+ " min-width:130px; background:white; font-size:1em;\"> <strong>"
				+ resource.getName() + "</strong>" + "<br/>";

		if (resource.getDescription() != null) {
			html += "Description: " + resource.getDescription() + "<br/>";
		}

		// Die letzten 3 Items Hinzufuegen
		html += "<div id=\"" + resourceVisualization.getURI().toString()
				+ "_rssItems\" style=\"font-size:0.9em;\" ";
		if (resource.getId() != null) {
			List<Item> itemList = getLatestItems("http://groupme.org/GroupMe/api/export.do?groupID=" + resource.getId() + "&mode=export-groups&export-format=rss");
			int i = 0;
			while (i < 5 && i < itemList.size()) {

				html += "<br/> <a href=\"" + itemList.get(i).getLink()
						+ "\" target=\"_blank\"" + "\" title=\"visit feed @ "
						+ itemList.get(i).getLink() + "\">";

						
						if (itemList.get(i).getDate() != null){
							html+= itemList.get(i).getDate()  + " - ";
						}else{
						html+= (i + 1) + ". - " ;
						}
						html+= itemList.get(i).getTitle() + "</a>";
				i++;
			}
			if (itemList.size() == 0) {
				html += "<br/> " + "<span style=\"font-size:2em;\">"
						+ "Problems parsing the feed or feed is empty"
						+ "</span>";
			}

		}
		html += "</div>";

		// URL hinzufügen
		if (resource.getURL() != null) {
			html += "<br/>URL: <a href=\"" + resource.getURL()
					+ "\" target=\"_blank\"" + "\" title=\"visit resource @ "
					+ resource.getURL() + "\">" + formatURL(resource.getURL())
					+ "</a>";
		}
		// close div _content
		html += "</div>";
		// div open _tags
		html += "<div id=\"" + resourceVisualization.getURI().toString()
				+ "_tags\" class=\"tag\" style=\"display:none;\">";
		// close div _tags
		html += "</div>";
		// close div URI
		html += "</div>";
		html += this.getMoveBar(resourceVisualization, widthMove);
		// close div _border
		html += "</div>";
		return html;
	}

	/**
	 * Transforms a URL to a string with a maximal length. Example:
	 * 
	 * <pre>
	 *  http://abc.de/bliblablup/bliblablup/feuerwehrmann.html
	 * </pre>
	 * 
	 * ...will be transformed into:
	 * 
	 * <pre>
	 *  ..lup/feuerwehrmann.html
	 * </pre>
	 * 
	 * @param url
	 *            the url to be formatted
	 * @return a shortened version of the URL as a String
	 */
	private static final String formatURL(URL url) {
		String formatted = url.toString();
		if (formatted.length() > 40) {
			formatted = "..." + formatted.substring(formatted.length() - 39);
		}
		return formatted;

	}

	public List<Item> getLatestItems(String rssURL) {
		ChannelIF channel = null;
		if (rssURL == null) {
			return new ArrayList<Item>();
		}
		try {
			channel = FeedParser.parse(new ChannelBuilder(), rssURL);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

			return new ArrayList<Item>();
		}

		Iterator iter = channel.getItems().iterator();
		List<Item> itemList = new ArrayList<Item>();
		while (iter.hasNext()) {

			itemList.add(((Item) iter.next()));
		}

		return itemList;

	}

}
